感謝https://javascript30.com/的免費教程
學習點:
JS陣列
const inventors = [
      { first: 'Albert', last: 'Einstein', year: 1879, passed: 1955 },
      { first: 'Isaac', last: 'Newton', year: 1643, passed: 1727 },
      { first: 'Galileo', last: 'Galilei', year: 1564, passed: 1642 },
      { first: 'Marie', last: 'Curie', year: 1867, passed: 1934 },
      { first: 'Johannes', last: 'Kepler', year: 1571, passed: 1630 },
      { first: 'Nicolaus', last: 'Copernicus', year: 1473, passed: 1543 },
      { first: 'Max', last: 'Planck', year: 1858, passed: 1947 }
    ];
1.要過濾1500~1600年以外的人,使用filter
// 1. Filter the list of inventors for those who were born in the 1500's
    const bornFilter=inventors.filter(inventor=>(inventor.year>=1500 && inventor.year<=1600));
    console.table(bornFilter);
// Array.prototype.map()
    // 2. Give us an array of the inventory first and last names
    const nameArray=inventors.map(inventor=>`${inventor.first} ${inventor.last}`);
    console.log(nameArray);
3.生日的排序,對於排序可直接使用sort
    // 3. Sort the inventors by birthdate, oldest to youngest
    const sortBirthday=inventors.sort((a,b)=>(a.year>b.year)?1:-1);
    console.table(sortBirthday);
    // Array.prototype.reduce()
    // 4. How many years did all the inventors live?
    const reduceInventor=inventors.reduce((a,year)=>{
      return a+(year.passed - year.year);}
      ,0);
    console.log(reduceInventor);
4.計算陣列中總數,要假設陣列中的物品都是不知道的,則a代表容器,b代表物品。還在摸索中(抓頭)
// 8. Reduce Exercise
    // Sum up the instances of each of these
    const data = ['car', 'car', 'truck', 'truck', 'bike', 'walk', 'car', 'van', 'bike', 'walk', 'car', 'van', 'car', 'truck' ];
    const sumObject = data.reduce((a,b)=>{
      if(!a[b]) a[b]=0;
      a[b]++;
      return a;
    },{});
    console.log(sumObject);